package comm;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;


public class UdpBroadcaster implements Runnable{

	private MulticastSocket socket;
	private InetAddress group;
	private NetworkInterface ni;

	public UdpBroadcaster(NetworkInterface ni, int port, String groupName) throws IOException{

		//setting up socket
		this.ni = ni;
		socket =  new MulticastSocket(port);
		group = InetAddress.getByName(groupName);
	}

	@Override
	public void run() {
		//join the group on the network interface
		try{
			socket.setNetworkInterface(ni);
			socket.joinGroup(group);
		}
		catch(SocketException e){
			System.out.println("Socket Exception on interface: "+ni.getDisplayName() +" in the Broadcaster");
			System.out.println("Group: "+group.getHostAddress());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendPacket(byte[] data, int dstPort) throws IOException{
		//creating and sending packet
		if (!socket.isClosed()){
			DatagramPacket sendPacket = new DatagramPacket(data, data.length, group, dstPort);
			socket.send(sendPacket);
		}
		else{
			System.out.println("The socket is closed.");
		}
	}
	public void close(){
		socket.close();
	}


}
